<template>
  <div>
    <newRadio :list="data.newRadioList"></newRadio>
    <toplist id="list" :list="data.topList" v-loading="data.loading"></toplist>
    <pagination
      v-if="data.topList.length"
      :endPage="data.pagination.endPage"
      :currentPage="data.pagination.page"
      :click="pageChange"
    ></pagination>
  </div>
</template>

<script setup lang="ts">
import { reqNewPrograms, reqRadioTopList } from '../../../api'
import newRadio from '../../../components/DjRadio/newRadio.vue';
import toplist from '../../../components/DjRadio/toplist.vue';
import pagination from '../../../components/pagination.vue';
import { useRouter } from 'vue-router'
import { ref, onMounted, watch } from 'vue'
import { DjRadioType, PaginationType } from '../../../types/types'
import { pageScrollTop } from '../../../utils'

const router = useRouter()

const query = router.currentRoute.value.query
const id = query.id?.toString()

type dataType = {
  newRadioList: DjRadioType[],
  topList: DjRadioType[],
  pagination: PaginationType,
  loading: boolean,
}
const data = ref<dataType>({
  newRadioList: [],
  topList: [],
  pagination: {
    total: 0,
    page: 1,
    endPage: 0,
  },
  loading: false
})

//获取优秀新电台
const getNewRadioList = () => {
  if (!id) return
  reqNewPrograms(id)
    .then(res => {
      console.log(res)
      data.value.newRadioList = res.djRadios.slice(0, 5)
    })
}

//获取电台排行榜 ，limit=32 默认
const getRadioTopList = () => {
  if (!id) return
  data.value.loading = true
  reqRadioTopList(id, data.value.pagination.page)
    .then(res => {
      console.log(res)
      data.value.topList = res.djRadios
      data.value.pagination = {
        ...data.value.pagination,
        total: res.count,
        endPage: Math.ceil(res.count / 32),
      }
      data.value.loading = false
      console.log(data.value)
    })
}

//页数改变
const pageChange = (type: 'prev' | 'page' | 'next', page?: number) => {
  let current = data.value.pagination.page
  const end = data.value.pagination.endPage
  if (type === 'page' && page) {
    const handler = {
      prev: () => data.value.pagination.page = current === 1 ? current : current - 1,
      page: () => data.value.pagination.page = page,
      next: () => data.value.pagination.page = current === end ? end : current + 1,
    }
    handler[type]()
  }
}

//跳转至排行榜头部
const jumpTopList = function () {
  let h = document.getElementById("list")?.offsetTop
  if (h) pageScrollTop(h)
}

onMounted(() => {
  getNewRadioList()
  getRadioTopList()
})

watch(() => data.value.pagination.page, () => {
  getRadioTopList()
  jumpTopList()
})
</script>

<style lang="scss" scoped>
</style>